package com.hyc.myvideo.ui.activity.my;

import android.app.Activity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.acmenxd.toaster.Toaster;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hyc.myvideo.R;
import com.hyc.myvideo.data.adapter.my.recharge.PackageAdapter;
import com.hyc.myvideo.data.api.constants.Constants;
import com.hyc.myvideo.data.api.model.BaseResult;
import com.hyc.myvideo.data.api.model.UserInfo;
import com.hyc.myvideo.data.api.model.VipPackage;
import com.hyc.myvideo.ui.base.BaseFActivity;
import com.hyc.myvideo.ui.view.DialogPay;
import com.hyc.myvideo.utils.imguitl.ImgUitl;
import com.hyc.myvideo.widget.CommonListView;
import com.hyc.pay.alipay.Alipay;
import com.hyc.pay.alipay.PayResult;
import com.hyc.pay.wxpay.OrderInfoUtil;
import com.hyc.pay.wxpay.Wxpay;
import com.hyc.utils.StringUtils;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;

import java.util.List;

import butterknife.BindView;
import timber.log.Timber;


/**
 * 充值会员
 * @author gyb
 * @version 1.0
 * @created 2017/07/12
 */
public class RechargeActivity extends BaseFActivity implements PackageAdapter.Callback{
    /**展示会员信息*/
    @BindView(R.id.l_vip_id)LinearLayout linearLayoutVIP;
    @BindView(R.id.l_layout) LinearLayout layout;
    /**头像*/
    @BindView(R.id.image_head_id)
    ImageView imageViewHead;
    /**昵称*/
    @BindView(R.id.t_vip_nickname_id)
    TextView textViewNickname;
    /**剩余天数*/
    @BindView(R.id.t_vip_days_id) TextView textViewDays;
    /**标记*/
    @BindView(R.id.t_vip_mark) TextView textViewVip;

    /**展示会员购买列表*/
    @BindView(R.id.r_list_id)
    CommonListView commonListView;
    /**支付选择弹框*/
    private DialogPay dialogPay = null;
    /**购买信息*/
    private VipPackage vipPackage = null;
    /**支付方式*/
    private String payType = "";
    @Override
    public int getContentViewId() {
        return R.layout.activity_recharge;
    }

    @Override
    protected void initView() {
        setLeftBtnClick(true,getStr(R.string.huc_my_recharge));
        showVIP(userInfo);
        dialogPay = new DialogPay(payInterface);
    }

    @Override
    protected void initData() {
        api.userBuyVIP();
    }

    @Override
    protected void oNext(String r, String method){
        //购买列表
        if(method.equalsIgnoreCase(Constants.API_USER_RECHARGE)){
            BaseResult<List<VipPackage>> result = JSONObject.parseObject(r, new TypeReference<BaseResult<List<VipPackage>>>(){});
            if(result.isCode()){
                layout.setVisibility(View.VISIBLE);
                commonListView.setAdapter(new PackageAdapter(this,result.getResult(),this));
            }
        }
        //支付
        if(method.equalsIgnoreCase(Constants.API_PAY)){
            if(payType.equalsIgnoreCase(Constants.PAY_WXPAY)){
                doWxpay(this,"");
            }else{
                doAlipay(this,"");
            }
        }
        //查询用户信息
        if(method.equalsIgnoreCase(Constants.API_USERINFO)){
            BaseResult<UserInfo> result = JSONObject.parseObject(r, new TypeReference<BaseResult<UserInfo>>(){});
            if(result.isCode()){
                Toaster.show("支付成功");
                UserInfo userInfo = result.getResult();
                showVIP(userInfo);
                appContext.setUserInfo(userInfo);
            }
        }

    }

    @Override
    protected void oError() {

    }

    /**
     * 展示会员信息
     */
    private void showVIP(UserInfo userInfo){
        //判断是否VIP
        if(userInfo.getUser_vip_state() > 0){
            linearLayoutVIP.setVisibility(View.VISIBLE);
            textViewNickname.setText(userInfo.getUser_nickname());
            textViewDays.setText(String.format(getString(R.string.huc_my_vip_days),userInfo.getUser_surplus_day()));
            ImgUitl.setLocalRoundImg(userInfo.getUser_face(),imageViewHead,R.dimen.app_headImg);
            textViewVip.setText(userInfo.getVip_name());
        }else{
            linearLayoutVIP.setVisibility(View.GONE);
        }
    }

    @Override
    public void click(View v) {
        vipPackage = (VipPackage) v.getTag();
        Timber.i(payType+"============vipPackage===================="+vipPackage.toString());
        dialogPay.show(getSupportFragmentManager(), "支付选择");
    }

    /***
     * 支付选择
     */
    DialogPay.PayInterface payInterface = new DialogPay.PayInterface() {
        @Override
        public void OnClickWxpay() {
            payType = Constants.PAY_WXPAY;
            api.requestPay(2,payType,vipPackage.getVip_id());
        }

        @Override
        public void OnClickAlipay() {
            payType = Constants.PAY_ALIPAY;
            api.requestPay(2,payType,vipPackage.getVip_id());
        }
    };



    /***
     * 支付宝
     * @param activity
     * @param orderInfo 支付信息字符串
     */
    public  void doAlipay(Activity activity, String orderInfo) {
        Alipay alipay = new Alipay(activity);
        alipay.setPayListener(new Alipay.PayListener() {
            @Override
            public void onPaySuccess(PayResult payResult) {
                //Toaster.show("支付成功");
                api.requestUserInfo();
            }
            @Override
            public void onPayWaiting(PayResult payResult) {
                Toaster.show("支付结果确认中...");
            }

            @Override
            public void onPayCancel(PayResult payResult) {
                Toaster.show("您已取消支付");
            }

            @Override
            public void onPayFailure(PayResult payResult) {
                Toaster.show("支付失败\n" + payResult.getMemo());
            }
        });
        if (StringUtils.isEmpty(orderInfo)) {
                Toaster.show("缺少配置，无法支付");
            return;
        }
        alipay.payV2(orderInfo);

//        if (TextUtils.isEmpty(orderInfo)) {
//            // set v1 config
//            Alipay.DEBUG = true;
//            Alipay.Config.appId = "";
//            Alipay.Config.rsa_private = "";
//            Alipay.Config.rsa_public = "";
//            Alipay.Config.notify_url = "app/pay/alipay_notify.do";
//
//            if (!alipay.check()) {
//                Toaster.show("缺少配置，无法支付");
//                return;
//            }
//            String trans_order_id = OrderInfoUtil2_0.genOutTradeNo();
//            Map<String, String> map = OrderInfoUtil2_0.buildOrderParamMap(trans_order_id, "测试支付", "测试商品1，测试商品2",
//                    String.valueOf(0.01f), null);
//            orderInfo = OrderInfoUtil2_0.getOrderInfo(map);
//            alipay.payV1(orderInfo);
//        }
//        else {
//            alipay.payV2(orderInfo);
//        }
    }

    /***
     * 微信支付
     * @param activity
     * @param orderInfo
     */
    public  void doWxpay(Activity activity,String orderInfo) {
        // 获取支付类
        Wxpay wxpay = Wxpay.getInstance(activity);
        // 设置支付回调监听
        wxpay.setPayListener(new Wxpay.PayListener() {
            @Override
            public void onPaySuccess(BaseResp resp) {
                //Toaster.show("支付成功");
                api.requestUserInfo();
            }

            @Override
            public void onPayCanceled(BaseResp resp) {
                Toaster.show("支付取消");
            }

            @Override
            public void onPayFailure(BaseResp resp) {
                Toaster.show("支付失败");
            }
        });
        // 这里是服务端下单，内容是统一下单返回的xml
        if (StringUtils.isEmpty(orderInfo)) {
            Toaster.show("缺少配置，无法支付");
            return;
        }
        PayReq req = OrderInfoUtil.getPayReq(orderInfo);
        wxpay.pay(req);

//        else { // 客户端下单
//            Wxpay.DEBUG = true; // 开启日志
//            // API密钥，在微信商户平台设置
//            Wxpay.Config.api_key = "ganzhoualpha112114115WXZHOUALPHA";
//            // APPID，在微信开放平台创建应用后生成
//            Wxpay.Config.app_id = "wx14af47ab474a0991";
//            // 商户ID，注册商户平台后生成
//            Wxpay.Config.mch_id = "1415675302";
//            // 支付结果异步通知接口，由后台开发提供
//            Wxpay.Config.notify_url = "http://www.ieclipse.cn/app/pay/wxpay_notify.do";
//            // 创建统一下单异步任务
//            Wxpay.DefaultOrderTask task = new Wxpay.DefaultOrderTask(wxpay);
//            // 这个商户订单号，由后台返回，在这里随便生成一个
//            String outTradeNo = OrderInfoUtil2_0.genOutTradeNo();
//            // 设置统一下单的请求参数
//            task.setParams(OrderInfoUtil.buildOrderParamMap(outTradeNo, "测试支付", "", "1", null, null, null));
//            task.execute();
//        }
    }
}
